﻿using Ionic.Zip;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace ESPL.CodeGenerator.Domain.Utilities
{
    public class ZipHelper
    {
        public static bool UnzipFile(string sourceFile,string destinationDirectory)
        {
            if (!File.Exists(sourceFile)) return false;
            if (!Directory.Exists(destinationDirectory)) return false;

            byte[] buffer = new byte[2048];
            int n;
            using (var input = new ZipInputStream(sourceFile))
            {
                ZipEntry entry;
                while ((entry = input.GetNextEntry()) != null)
                {
                    if (entry.IsDirectory)
                    {
                        DirectoryHelper.CreateDirectory(string.Format("{0}/{1}",destinationDirectory, entry.FileName));
                    }
                    else
                    {
                        string outputPath = Path.Combine(destinationDirectory, entry.FileName);
                        using (var output = File.Open(outputPath, FileMode.Create, FileAccess.ReadWrite))
                        {
                            while ((n = input.Read(buffer, 0, buffer.Length)) > 0)
                            {
                                output.Write(buffer, 0, n);
                            }
                        }
                    }
                }
            }

            return true;
        }

        public static bool ZipFolder(string sourceFolderName, string destinationDirectory,string zipFileName)
        {
            if (!Directory.Exists(sourceFolderName)) return false;
            if (!Directory.Exists(destinationDirectory)) return false;

            var outputFileDirName = destinationDirectory+"\\"+zipFileName;
            using (ZipFile zip = new ZipFile())
            {
                zip.AddDirectory(sourceFolderName, "SampleApp");
                zip.Comment = "This zip was created at " + System.DateTime.Now.ToString("G");
                zip.Save(outputFileDirName);
            }

            return true;
        }
    }
}
